package edu.gatech.cs2340.group7.wheresmystuffapp.presenters;

import java.util.List;
import edu.gatech.cs2340.group7.wheresmystuffapp.model.DatabaseHelper;
import edu.gatech.cs2340.group7.wheresmystuffapp.model.Item;
import edu.gatech.cs2340.group7.wheresmystuffapp.model.ItemManager;
import edu.gatech.cs2340.group7.wheresmystuffapp.views.DisplaySearchResultsView;

/**
 * Logic for displaying search results
 * @author Magic 7
 *
 */
public class DisplaySearchResultsPresenter {

	private DisplaySearchResultsView view;
	private String searchParams;
	private ItemManager manager;
	
	/**
	 * constructor for the class
	 * @param v the view of the screen
	 */
	
	public DisplaySearchResultsPresenter(DisplaySearchResultsView v) {
		this.view = v;
		manager = new ItemManager();
	}

	/**
	 * Searches for items and displays the results
	 * 
	 * @param searchParameters
	 *            What the user is searching for
	 */
	public void showSearchResults(String searchParameters) {
		searchParams = searchParameters;
		DatabaseHelper helper = new DatabaseHelper(view);
		List<Item> items = helper.getAllItems();
		System.out.println("There are: " + items.size() + " items");
		System.out.println("Search Parameters: " + searchParams);
		String searchString = "";

		// filter items
		try {
			if (searchParams.equalsIgnoreCase("Keepsake")) {
				System.out.println("Attempting to filter");
				items = manager.filterItemsByCategory(items, "Keepsake");
			} else if (searchParams.equalsIgnoreCase("Heirloom")) {
				items = manager.filterItemsByCategory(items, "Heirloom");
			} else if (searchParams.equalsIgnoreCase("Misc")
					|| searchParams.equalsIgnoreCase("Miscellaneous")) {
				items = manager.filterItemsByCategory(items, "Misc");
			} else {
				items = manager.filterByName(items, searchParameters);
			}

			// convert item names to a single string

			if (!items.isEmpty()) {
				for (Item item : items) {
					searchString += item.getName() + '\n';
				}
			}
		} catch (NullPointerException E) {
			searchString = "No items available";
		}

		// tell view to display the string
		view.setSearchResults(searchString);
	}

}
